import time
from pywifi import PyWiFi, const, Profile

def list_available_networks():
    wifi = PyWiFi()
    iface = wifi.interfaces()[0]

    iface.scan()
    time.sleep(2)  # 等待扫描完成

    scan_results = iface.scan_results()
    networks = []

    for network in scan_results:
        networks.append({
            'ssid': network.ssid.encode('raw_unicode_escape').decode('utf-8'),
            'signal': network.signal,
            'bssid': network.bssid,
            'frequency': network.freq
        })

    return networks



def connect_to_wifi(ssid, bssid=None, password=None):
    wifi = PyWiFi()
    iface = wifi.interfaces()[0]

    iface.disconnect()
    time.sleep(1)  # 等待断开连接

    profile = Profile()
    profile.ssid = ssid
    if bssid:
        profile.bssid = bssid

    if password:
        profile.auth = const.AUTH_ALG_OPEN
        profile.akm.append(const.AKM_TYPE_WPA2PSK)
        profile.cipher = const.CIPHER_TYPE_CCMP
        profile.key = password
    else:
        profile.auth = const.AUTH_ALG_OPEN
        profile.akm.append(const.AKM_TYPE_NONE)
        profile.cipher = const.CIPHER_TYPE_NONE

    iface.remove_all_network_profiles()
    tmp_profile = iface.add_network_profile(profile)

    iface.connect(tmp_profile)
    time.sleep(10)  # 等待连接完成

    if iface.status() == const.IFACE_CONNECTED:
        print(f"已连接到 {ssid} ({bssid})")
    else:
        print(f"连接到 {ssid} ({bssid}) 失败")

def disconnect_wifi():
    wifi = PyWiFi()
    iface = wifi.interfaces()[0]
    iface.disconnect()
    time.sleep(1)  # 等待断开连接

    if iface.status() != const.IFACE_DISCONNECTED:
        print("断开连接失败")
    else:
        print("已断开连接")


# 示例用法
available_networks = list_available_networks()
for network in available_networks:
    print(f"SSID: {network['ssid']}, 信号强度: {network['signal']}, BSSID: {network['bssid']}, 频率: {network['frequency']}")

ssid = 'SQNU'
bssid = 'fe:2b:a6:94:eb:e0'
password = None  # Add the password if the network is secured

connect_to_wifi(ssid, bssid, password)